import sys
import numpy as np
import cv2
from PIL import Image,ImageDraw,ImageFont
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5 import QtGui
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMessageBox
import json
import datetime

sys.path.append("../")
from plate_detect.plate_detect import PlateDetect
from UI.select_file_ui import Ui_MainWindow
from database.database import DataBase

class Window(QMainWindow, Ui_MainWindow):

    def __init__(self, uid=1, path=r"../plate_detect/ultralytics/weights/best.pt", db_path = "../database/plave_data.db"):
        super(Window, self).__init__()
        self.setupUi(self)
        self.input.setScaledContents(True)
        self.input.clear()
        self.plate_engine = PlateDetect(path)
        self.frame = np.zeros((846, 621, 3), dtype="uint8")
        self.next_dish = ""
        self.count = 0
        self.dish_list = []
        self.database = DataBase(db_path)
        self.uid = uid

    def msg(self, Filepath):
        fileName, fileType = QtWidgets.QFileDialog.getOpenFileName(None, "选取文件", "./", "All Files (*);;Text Files (*.txt)")
        self.fileT.setText(fileName)
        self.timer_camera = QTimer()  # 定义定时器，用于控制显示视频的帧率
        self.cap = cv2.VideoCapture(fileName)
        # self.cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
        self.timer_camera.start(25)
        self.timer_camera.timeout.connect(self.frame_flash)

    def frame_flash(self):
        try:
            ret, self.frame = self.cap.read()  # 定义，读取摄像头内容
            frame, total, self.dish_list = self.plate_engine.detect_frame(self.frame)
            pil_img = Image.fromarray(cv2.cvtColor(frame,cv2.COLOR_BGR2RGB))
            draw = ImageDraw.Draw(pil_img)
            font = ImageFont.truetype('simhei.ttf', 100, encoding="utf-8")
            draw.text((50,200), f"总价：{total}", (255,0,0), font)
            frame = cv2.cvtColor(np.array(pil_img),cv2.COLOR_RGB2BGR)
            show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            image = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
            self.input.setPixmap(QPixmap.fromImage(image))
            if str(self.dish_list) == self.next_dish and total != 0:
                self.count += 1
            else:
                self.next_dish = str(self.dish_list)
                self.count = 0

            
            print(f"count: {self.count}")
        except Exception as e:
            self.timer_camera.stop()
            self.count = 0
            self.next_dish = ""
            print(self.dish_list)
            reply = QMessageBox.warning(None, '消息','测试完毕', QMessageBox.Yes)
            if int(reply) == 16384:
                self.close()
        
        if self.count >= 80:
            self.timer_camera.stop()
            self.count = 0
            self.next_dish = ""
            print(self.dish_list)
            defaultBtn = QMessageBox.NoButton
            reply = QMessageBox.question(self, "支付", f"请支付{total}元", QMessageBox.Yes | QMessageBox.No |QMessageBox.Cancel,defaultBtn)
            print(reply)
            # 16384 
            # 65536
            # 4194304
            print(type(int(reply)))
            if int(reply) == 16384:
                currentDateTime = datetime.datetime.now()
                data = (self.uid, total, json.dumps(self.dish_list), currentDateTime)
                self.database.insert_record(data)
            
            self.timer_camera.start()
                
        

if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = Window()
    MainWindow.show()
    sys.exit(app.exec_())
